#coding:utf-8
from bottle import abort
class Pager:
    def __init__(self, model=None, query=None, page_length=10):
        if model:
            self.query = model.all()
        if query:
            self.query = query
        self.page_length = page_length

    def fetch(self, curpage=1):
        curpage = int(curpage)
        if hasattr(self.query, '__len__'):
            self.count = len(self.query)
        else:
            self.count = self.query.count()

        if self.count < (curpage -1 ) * self.page_length:
            abort(404)
        pagenum = self.count / self.page_length
        if self.count % self.page_length != 0:
            pagenum += 1
        offset = (curpage - 1) * self.page_length

        if hasattr(self.query,'fetch'):
            results = self.query.fetch(self.page_length, offset)
        else:
            results = self.query[offset:offset+self.page_length]
        
        links = {'count':self.count, 'page_index': curpage, 'prev': curpage - 1, 'next': curpage + 1, 'last': pagenum}
        if links['next'] > pagenum:
            links['next'] = 0
        return (results, links)